
package com.greenant.store.version;

import java.io.File;

import com.greenant.store.version.DownloadManager.UpdateShared;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 */
public class DownloadInstall implements DownloadCallback {

    private Context mContext;
    private String apkPath, apkVersion;
    private int apkCode;
    private LayoutInflater inflater;

    private TextView textView;
    private ProgressBar progressView;
    private boolean interceptFlag = false; // 是否取消下载
    private final static String TAG = "DownloadInstall";

    public DownloadInstall(Context mContext, String apkPath, String apkVersion,
            int apkCode) {
        this.mContext = mContext;
        this.apkCode = apkCode;
        this.apkPath = apkPath;
        this.apkVersion = apkVersion;
        inflater = LayoutInflater.from(mContext);
    }

    public DownloadInstall(Context mContext, String apkPath, String apkVersion) {
        this.mContext = mContext;
        this.apkPath = apkPath;
        this.apkVersion = apkVersion;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public boolean onCancel() {
        return interceptFlag;
    }

    @Override
    public void onChangeProgress(int progress) {
        // progressView.setProgress(progress); //设置下载进度
        // textView.setText("进度："+progress+"%");
    }

    @Override
    public void onCompleted(boolean success, String errorMsg) {
        if (success) { // 更新成功
            installApk();
        } else {
            Toast.makeText(mContext, errorMsg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onDownloadPreare() {
//        if (IntentUtil.checkSoftStage(mContext)) {
//          
//        }
    }

    /**
     * 升级成功，更新升级日期和版本号，和版本code
     */
    private void alearyUpdateSuccess() {
        SharedPreferences sharedPreference = mContext.getSharedPreferences(
                UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        sharedPreference.edit().putString(UpdateShared.APK_VERSION, apkVersion)
                .putInt(UpdateShared.APK_VERCODE, apkCode).commit();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File file = new File(apkPath);
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
